<?php


namespace App\Http\Rest\Admin\Resource;

use App\Http\Rest\Admin\DbResource;
use Com\Alibaba\Otter\Canal\Protocol\EventType;
use Framework\Foundation\Database\FDB;
use think\facade\Db;
use Framework\Foundation\Response\ResponseGen;

class DddEventStream extends DbResource
{
    public function getList(array $restParams, $request)
    {
        $search = $request->getIn('search');

        $page = $request->getIn('pageNumber', 1);
        $pageSize = $request->getIn('pageSize', 10);

        $query = Db::table($restParams['resource'])
            ->order($restParams['field'] . ' desc ')
            ->where('is_deleted', '=', 0);
        if (!empty($search)) {
            $query->whereLike('db_name', '%' . $search . '%', 'or');
            $query->whereLike('table_name', '%' . $search . '%', 'or');
            $query->whereLike('transaction_tag', '%' . $search . '%');
        }


        $total = $query->count();
        $query = $query->limit($pageSize * ($page - 1), $pageSize);
        $ret = $query->select()->toArray();

        if (!empty($ret)) {
            foreach ($ret as $k => $v) {
                $ret[$k]['event_name'] = EventType::name($v['event_type']);
            }
        }

        return ResponseGen::success(['total' => $total, 'rows' => $ret]);
    }

    public function delete(array $restParams)
    {
        $remainIds = $this->getRemainIds();
        Db::table($restParams['resource'])->whereNotIn($restParams['field'], $remainIds)->delete(true);
        return ResponseGen::success();
    }

    public function getRemainIds()
    {
        $list = Db::table('ddd_event')->select()->toArray();
        $array = [];
        if (empty($list)) {
            return $array;
        }

        foreach ($list as $k => $v) {
            $ids = $v['stream_ids'];
            if (!empty($ids)) {
                $tempArray = explode(',', $ids);
                $array = array_merge($array, $tempArray);
            }
        }

        return array_unique($array);
    }
}
